package com.xhc.demo.utils;

import org.springframework.stereotype.Component;

/**
 * 雪花算法ID生成器
 * 结构：1位符号位 + 41位时间戳 + 10位机器ID + 12位序列号
 */
@Component
public class SnowflakeIdGenerator {
    // 开始时间戳（2025-01-01 00:00:00）
    private final long START_TIMESTAMP = 1735660800000L;
    
    // 机器ID所占位数
    private final long WORKER_ID_BITS = 10L;
    // 序列号所占位数
    private final long SEQUENCE_BITS = 12L;
    
    // 机器ID最大值 (2^10 - 1 = 1023)
    private final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    // 序列号最大值 (2^12 - 1 = 4095)
    private final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);
    
    // 机器ID左移位数 (12)
    private final long WORKER_ID_SHIFT = SEQUENCE_BITS;
    // 时间戳左移位数 (22)
    private final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    
    // 机器ID (0-1023)
    private long workerId;
    // 序列号 (0-4095)
    private long sequence = 0L;
    // 上次生成ID的时间戳
    private long lastTimestamp = -1L;
    
    public SnowflakeIdGenerator() {
        // 默认使用0作为机器ID
        this(0L);
    }
    
    public SnowflakeIdGenerator(long workerId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID can't be greater than " + MAX_WORKER_ID + " or less than 0");
        }
        this.workerId = workerId;
    }
    
    /**
     * 生成下一个ID
     */
    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();
        
        // 如果当前时间小于上次生成ID的时间，说明系统时钟回退，抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id for " + (lastTimestamp - timestamp) + " milliseconds");
        }
        
        // 如果是同一时间生成的，则进行序列号自增
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            // 序列号用完了，等待下一毫秒
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            // 时间戳改变，序列号重置
            sequence = 0L;
        }
        
        lastTimestamp = timestamp;
        
        // 生成ID
        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_SHIFT) | // 时间戳部分
                (workerId << WORKER_ID_SHIFT) | // 机器ID部分
                sequence; // 序列号部分
    }
    
    /**
     * 等待下一毫秒
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
    
    /**
     * 将雪花ID转换为字符串格式的订单号
     */
    public String generateOrderNumber() {
        return String.format("%019d", nextId());
    }
}
